import {
  Controller,
  Get,
  Query,
  Res,
  UseGuards,
  BadRequestException,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiQuery } from '@nestjs/swagger';
import { Response } from 'express';
import { ReportsService } from './reports.service';
import { JwtAuthGuard } from '@/common/guards/jwt-auth.guard';
import { PermissionGuard } from '@/common/guards/permission.guard';
import { RequirePermissions } from '@/common/decorators/permission.decorator';
import * as dayjs from 'dayjs';

@ApiTags('报表管理')
@Controller('reports')
@UseGuards(JwtAuthGuard, PermissionGuard)
@ApiBearerAuth()
export class ReportsController {
  constructor(private readonly reportsService: ReportsService) {}

  @Get('user-stats')
  @RequirePermissions('reports:user-stats')
  @ApiOperation({ summary: '获取用户统计数据' })
  @ApiQuery({ name: 'startDate', required: false, description: '开始日期' })
  @ApiQuery({ name: 'endDate', required: false, description: '结束日期' })
  async getUserStats(
    @Query('startDate') startDate?: string,
    @Query('endDate') endDate?: string,
  ) {
    const start = startDate || dayjs().subtract(30, 'day').format('YYYY-MM-DD');
    const end = endDate || dayjs().format('YYYY-MM-DD');
    
    return this.reportsService.getUserStats(start, end);
  }

  @Get('payment-stats')
  @RequirePermissions('reports:payment-stats')
  @ApiOperation({ summary: '获取支付统计数据' })
  @ApiQuery({ name: 'startDate', required: false, description: '开始日期' })
  @ApiQuery({ name: 'endDate', required: false, description: '结束日期' })
  async getPaymentStats(
    @Query('startDate') startDate?: string,
    @Query('endDate') endDate?: string,
  ) {
    const start = startDate || dayjs().subtract(30, 'day').format('YYYY-MM-DD');
    const end = endDate || dayjs().format('YYYY-MM-DD');
    
    return this.reportsService.getPaymentStats(start, end);
  }

  @Get('system-stats')
  @RequirePermissions('reports:system-stats')
  @ApiOperation({ summary: '获取系统统计数据' })
  async getSystemStats() {
    return this.reportsService.getSystemStats();
  }

  @Get('export/users')
  @RequirePermissions('reports:export-users')
  @ApiOperation({ summary: '导出用户报表' })
  @ApiQuery({ name: 'startDate', required: true, description: '开始日期' })
  @ApiQuery({ name: 'endDate', required: true, description: '结束日期' })
  async exportUserReport(
    @Query('startDate') startDate: string,
    @Query('endDate') endDate: string,
    @Res() res: Response,
  ) {
    if (!startDate || !endDate) {
      throw new BadRequestException('开始日期和结束日期不能为空');
    }

    const buffer = await this.reportsService.exportUserReport(startDate, endDate);
    
    const filename = `用户报表_${startDate}_${endDate}.xlsx`;
    
    res.set({
      'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'Content-Disposition': `attachment; filename="${encodeURIComponent(filename)}"`,
      'Content-Length': buffer.length.toString(),
    });
    
    res.send(buffer);
  }

  @Get('export/payments')
  @RequirePermissions('reports:export-payments')
  @ApiOperation({ summary: '导出支付报表' })
  @ApiQuery({ name: 'startDate', required: true, description: '开始日期' })
  @ApiQuery({ name: 'endDate', required: true, description: '结束日期' })
  async exportPaymentReport(
    @Query('startDate') startDate: string,
    @Query('endDate') endDate: string,
    @Res() res: Response,
  ) {
    if (!startDate || !endDate) {
      throw new BadRequestException('开始日期和结束日期不能为空');
    }

    const buffer = await this.reportsService.exportPaymentReport(startDate, endDate);
    
    const filename = `支付报表_${startDate}_${endDate}.xlsx`;
    
    res.set({
      'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'Content-Disposition': `attachment; filename="${encodeURIComponent(filename)}"`,
      'Content-Length': buffer.length.toString(),
    });
    
    res.send(buffer);
  }
}